package com.zhang.backend.controller;

import com.zhang.backend.common.response.Result;
import com.zhang.backend.entity.FamilyTree;
import com.zhang.backend.entity.Person; // 【新增】导入 Person
import com.zhang.backend.service.FamilyTreeService;
import com.zhang.backend.service.PersonService; // 【新增】导入 PersonService
import com.zhang.backend.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 管理家谱项目本身 (FamilyTree)
 */
@RestController
@RequestMapping("/api/family-trees")
public class FamilyTreeController {

    @Autowired
    private FamilyTreeService familyTreeService;

    // 【新增】注入PersonService，用于查询成员
    @Autowired
    private PersonService personService;

    @GetMapping
    public Result<List<FamilyTree>> getAllFamilyTrees() {
        return Result.success(familyTreeService.list());
    }

    /**
     * 【新增】处理前端请求，获取指定家谱下的所有成员
     * @param familyId 家谱ID
     * @return 成员列表
     */
    @GetMapping("/{familyId}/persons")
    public Result<List<Person>> getPersonsByFamilyTreeId(@PathVariable Long familyId) {
        List<Person> persons = personService.getPersonsByFamilyTreeId(familyId);
        return Result.success(persons);
    }

    @PostMapping
    public Result<FamilyTree> createFamilyTree(@RequestBody FamilyTree familyTree) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        familyTree.setUserId(currentUserId);
        familyTree.setCreateTime(LocalDateTime.now());
        familyTree.setUpdateTime(LocalDateTime.now());
        familyTreeService.save(familyTree);
        return Result.success(familyTree);
    }

    /**
     * 处理编辑家谱的 PUT 请求
     * @param id 要编辑的家谱ID
     * @param familyTreeDetails 从前端传来的包含新名称和描述的对象
     * @return 更新后的家谱对象
     */
    @PutMapping("/{id}")
    public Result<FamilyTree> updateFamilyTree(@PathVariable Long id, @RequestBody FamilyTree familyTreeDetails) {
        // 从数据库中获取现有的家谱对象
        FamilyTree existingFamilyTree = familyTreeService.getById(id);
        if (existingFamilyTree == null) {
            return Result.failure(404, "FamilyTree not found");
        }

        // 更新需要修改的字段
        existingFamilyTree.setName(familyTreeDetails.getName());
        existingFamilyTree.setContentDesc(familyTreeDetails.getContentDesc());
        // 设置更新时间
        existingFamilyTree.setUpdateTime(LocalDateTime.now());

        // 保存更新
        familyTreeService.updateById(existingFamilyTree);
        return Result.success(existingFamilyTree);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteFamilyTree(@PathVariable Long id) {
        familyTreeService.removeById(id);
        return Result.success(null);
    }
}